package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//自定义数据源 从数据查询并校验用户的信息
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRoleService roleService;

    @Override
    public String getName() {
        return "myRealm";
    }

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 认证方法
     * @param token 身份令牌
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo
            (AuthenticationToken token) throws AuthenticationException {
        //获取身份信息
        String principal = (String) token.getPrincipal();
        //查询数据库是否存在该用户
        Employee employee = employeeService.selectByUsername(principal);
        if(employee != null){
            //认证信息对象(员工对象,真实密码,加盐规则, 规则名称)
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(employee.getUsername()),getName());
        }
        return null;
    }

    /**
     * 授权方法
     * @param principals 身份信息
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        //获取当前登陆用户的id
        Long id = employee.getId();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //如果当前登陆用户是超级管理员
        if(employee.getAdmin()){
            //添加所有的权限
            info.addStringPermission("*:*");
            //添加ADMIN的角色名称
            info.addRole("ADMIN");
        }else {
            //根据登陆用户的ID 获取并添加权限
            info.addStringPermissions(permissionService.selectByEmployeeId(id));
            //根据登陆用户的ID 获取并添加角色
            info.addRoles(roleService.selectRoleByEmployeeId(id));
        }
        //返回info信息
        return info;
    }
}
